let socket = '' // 存储 WebSocket 连接.
let timeoutObj = null  // 心跳定时器
let serverTimoutObj = null // 服务超时定时关闭
let lockReconnect = false // 是否真正建立了连接
let timeoutnum = null // 重新连接的定时器，  没连接上会一直重连，设置延迟避免请求过多
let addres = localStorage.getItem('addres')
let code = localStorage.getItem('code')

const socketConfig = {
  // url: 'ws://10.12.8.193:7788/Message',
  url: `ws://${addres}:${code}/Message`,
  retryTimeout: 20000 // 心跳时间 暂定20s
}


export const sendWebsocket = function (agentData, callback) {
  // global_callback = callback
  socketOnSend(agentData)
}


export const initWebSocket = function (url) {
  let weburl = url || socketConfig.url
  if (!window.WebSocket) { return }
  if (!socket) {
    socket = new WebSocket(weburl)
    socketOnOpen()
    socketOnClose()
    socketOnError()
    socketOnMessage()
  }
}

/**
 * 关闭websocket函数
 */
export const closeWebsocket = function () {
  if (socket) {
    socket.close()
  }
  clearTimeout(timeoutObj)
  clearTimeout(serverTimoutObj)
}

function socketOnSend(data) {
  socket.send(data)
}

function socketOnOpen() {
  socket.onopen = () => {
    console.log('socket连接成功')
    start()
  }
}

// 开启心跳
function start() {
  timeoutObj && clearTimeout(timeoutObj)
  serverTimoutObj && clearTimeout(serverTimoutObj)
  timeoutObj = setTimeout(() => {
    // 这里发送一个心跳，后端收到后返回一个心跳消息
    if (socket.readyState === 1) {
      // 如果连接正常  给后端发送指定消息
      socket.send(0)
      console.log('发送消息')
    } else {
      // 重连
      reconnect()
    }
    serverTimoutObj = setTimeout(() => {
      // 超时关闭连接
      socket.close()
    }, socketConfig.retryTimeout);
  }, socketConfig.retryTimeout);
}

// 重连
function reconnect() {
  if (lockReconnect) {
    return
  }
  lockReconnect = true
  timeoutnum && clearTimeout(timeoutnum)
  timeoutnum = setTimeout(() => {
    initWebSocket()
    lockReconnect = false
  }, 5000);
}

function socketOnClose() {
  socket.onclose = () => {
    console.log('socket已经关闭')
  }
}

function socketOnError() {
  socket.onerror = () => {
    reconnect()
    console.log('socket 连接失败')
  }
}

function socketOnMessage() {
  socket.onmessage = (e) => {
    console.log('e.data',e.data)
    reset()
  }
}

// 重置心跳
function reset() {
  // 清除时间
  clearTimeout(timeoutObj)
  clearTimeout(serverTimoutObj)
  // 重启心跳
  start()
}
